<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width" />
    <title>WebSocket 客户端</title>
</head>

<body>
<div>
    <input type="button" id="btnConnection" value="连接" />
    <input type="button" id="btnClose" value="关闭" />
    <input type="button" id="btnSend" value="发送" />
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
    var socket;
    $(function(){
        if(typeof(WebSocket) == "undefined") {
            alert("您的浏览器不支持WebSocket");
        }
        $("#btnConnection").click();
    });
    if(typeof(WebSocket) == "undefined") {
        alert("您的浏览器不支持WebSocket");
    }

    $("#btnConnection").click(function() {
        //实现化WebSocket对象，指定要连接的服务器地址与端口
        socket = new WebSocket("ws://127.0.0.1:8080/ws/zhangsan");
        //打开事件
        socket.onopen = function() {
            console.info("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.info(msg.data);
        };
        //关闭事件
        socket.onclose = function() {
            console.info("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.info("发生了错误");
        }
    });

    //发送消息
    $("#btnSend").click(function() {
        socket.send("这是来自客户端的消息" + location.href + new Date());
    });

    //关闭
    $("#btnClose").click(function() {
        socket.close();
    });
</script>
</body>

</html>